<template>
  <div style="height:100%;width:100%">
    <webview v-on:console-message="consoleMessage($event)" v-on:did-stop-loading="stopLoading($event)" class="webview" id="web_cd" disablewebsecurity :src='url'></webview>
    <div class="operation" @click="build">
      构建需求md
    </div>
    <div class="build" v-show="onBuild">
      {{title}}
    </div>
  </div>
</template>

<script>
var ipcRenderer;
if (window.require) {
  ipcRenderer = window.require("electron").ipcRenderer;
}
export default {
  data() {
    return {
      url: 'http://192.168.2.166',
      buildUrl: 'http://192.168.2.166/project-story-33.html',
      onBuild: false,
      xq: [],
      title: '',
      step: 0,
      stepIndex: 0,//需求index
      rwStepIndex: 0,//需求内任务遍历index
    };
  },
  mounted() {
    this.onBuild = false
    this.xq = []
    this.title = ''
    this.step = 0
    this.stepIndex = 0//需求index
    this.rwStepIndex = 0//需求内任务遍历index
  },
  methods: {
    buildFileDetail(data) {
      let txt = '## 需求内容\n\r';
      txt += '###   ' + data.title + '\n\r'
      txt += '| 需求地址<div style="width:100px"> | ' + data.url + '<div style="width:600px"> |\n'
      txt += '| :-------------------------------- | ------------------------------------------------------------ |\n'
      txt += '| __创建人__                        |                                                        |\n'
      txt += '| __审核人__                        |                                                        |\n'
      txt += '| __所属模块__                      |                                                      |\n'
      txt += '| __创建时间__                      |                                                    |\n'
      txt += '| __需求描述__                      | ' + (data.xqms ? data.xqms : ' 暂无') + ' |\n'
      txt += '| __验收标准__                      | ' + (data.ysbz ? data.ysbz : ' 暂无') + '|\n\r\n\r'

      txt += '## 任务分解\n\r'
      txt += '### 1.需求：[' + data.title + '](' + data.url + ')\n\r'
      if (data.rwlb) {
        for (let i = 0; i < data.rwlb.length; i++) {
          let b = data.rwlb[i]
          txt += '#### 1.' + (i + 1) + '任务：[' + b.name + '](' + b.url + ')\n\r'
          txt += '| 任务地址<div style="width:100px"> | ' + b.url + '<div style="width:600px"> |\n'
          txt += '| :-------------------------------- | ------------------------------------------------------------ |\n'
          txt += '| __任务描述__                      | ' + (b.rwms && b.rwms != undefined ? b.rwms : '无') + '   |\n'
          txt += '| __验收标准__                      | 无                                                           |\n'
          txt += '| __负责人__                        | ' + b.user + ' |\n'
          txt += '| __任务状态__                      |                                                        |\n'
          txt += '| __开始时间__                      |                                                    |\n'
          txt += '| __结束时间__                      |                                                    |\n'
          txt += '| __工时__                          |                                                             |\n\r\n\r'
        }
      }

      return txt;
    },
    buildFile() {
      for (let x = 0; x < this.xq.length; x++) {
        let xq1 = this.xq[x];
        const pattern = /[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}'；：""'。，、？\s]/g;
        let fileName = xq1.title.replace(pattern, "");
        ipcRenderer.send('create-file', {
          path: "C:/Users/DELL/Desktop/aworkBuild",
          name: fileName + '.md',
          data: this.buildFileDetail(xq1)
        })
      }


      this.onBuild = false
      this.xq = []
      this.title = ''
      this.step = 0
      this.stepIndex = 0//需求index
      this.rwStepIndex = 0//需求内任务遍历index
    },
    consoleMessage(e) {
      var msg = e.message;
      console.log(e)
      if (msg.indexOf("awork1::") == 0) {
        msg = msg.replace("awork1::", "");
        if (msg == 'finish') {
          this.title = '正在获取需求详细'
          this.step = 2
          this.loadXQDetail();
        }
        let dom = document.createElement('div');
        dom.innerHTML = msg;
        let as = dom.querySelectorAll('a')
        if (as.length >= 3) {
          console.log()
          console.log()
          console.log(as[1].innerHTML)
          console.log(dom)
          console.log()
          console.log()
          this.xq.push({
            url: this.url + as[1].getAttribute("href"),
            title: as[1].innerHTML,
            rwUrl: this.url + '/story-tasks-' + as[0].innerHTML + '.html'
          })
        }
      }

      //需求详情
      if (msg.indexOf("awork2::") == 0) {
        msg = msg.replace("awork2::", "");
        let dom = document.createElement('div');
        dom.innerHTML = msg;

        let contents = dom.querySelectorAll(".detail-content");
        let articles = dom.querySelectorAll(".histories-list .article-content");

        let xqms = contents[0].innerText.replace(/(^\s*)|(\s*$)/g, "").replace(/\r\n+/g, '<br/> ')
        xqms = xqms.replace(/\n+/g, '<br/> ')
        let ysbz = contents[1].innerText.replace(/(^\s*)|(\s*$)/g, "").replace(/\r\n+/g, '<br/> ')
        ysbz = ysbz.replace(/\n+/g, '<br/> ')

        this.xq[this.stepIndex].xqms = xqms
        this.xq[this.stepIndex].ysbz = ysbz
        this.xq[this.stepIndex].xxsj = ''
        for (let i = 0; i < articles.length; i++) {
          let xxsj = articles[i].innerText.replace(/(^\s*)|(\s*$)/g, "").replace(/\r\n+/g, '<br/> ')
          xxsj = xxsj.replace(/\n+/g, '<br/> ')
          this.xq[this.stepIndex].xxsj += xxsj + '<br/> '
        }

        this.stepIndex++;
        this.loadXQDetail();
      }

      //任务列表
      if (msg.indexOf("awork3::") == 0) {
        msg = msg.replace("awork3::", "");
        let table = document.createElement('table');
        let tbody = document.createElement('tbody');
        table.appendChild(tbody)
        tbody.innerHTML = msg;
        let trs = tbody.querySelectorAll("tr");

        this.xq[this.stepIndex].rwlb = []
        for (let i = 0; i < trs.length; i++) {
          let tds = trs[i].querySelectorAll("td");
          if (!tds[3] || tds[3].innerHTML === '已取消') {
            continue
          }
          this.xq[this.stepIndex].rwlb.push({
            id: tds[0].innerHTML,
            name: tds[1].innerHTML,
            user: tds[4].innerHTML,
            url: this.url + '/task-view-' + tds[0].innerHTML + '.html'
          })
        }

        this.stepIndex++;
        this.loadRWDetail();
      }

      //任务详情
      if (msg.indexOf("awork4::") == 0) {
        msg = msg.replace("awork4::", "");
        let dom = document.createElement('div');
        dom.innerHTML = msg;

        let contents = dom.querySelectorAll(".detail-content");
        let articles = dom.querySelectorAll(".histories-list .article-content");

        let rwms = contents[0].innerText.replace(/(^\s*)|(\s*$)/g, "").replace(/\r\n+/g, '<br/> ')
        rwms = rwms.replace(/\n+/g, '<br/> ')


        this.xq[this.stepIndex].rwlb[this.rwStepIndex].rwms = rwms
        this.xq[this.stepIndex].rwlb[this.rwStepIndex].xxsj = ''
        for (let i = 0; i < articles.length; i++) {
          let xxsj = articles[i].innerText.replace(/(^\s*)|(\s*$)/g, "").replace(/\r\n+/g, '<br/> ')
          xxsj = xxsj.replace(/\n+/g, '<br/> ')
          this.xq[this.stepIndex].rwlb[this.rwStepIndex].xxsj += xxsj + '<br/> '
        }


        let ls = dom.querySelectorAll(".histories .histories-list li");
        for (let i = 0; i < ls.length; i++) {
          let ld = ls[i].innerHTML.split('。')[0]
          if (ld.indexOf(' 完成') > 0) {
            let name = ls[i].querySelector('strong').innerHTML
            if (name) {
              this.xq[this.stepIndex].rwlb[this.rwStepIndex].user = name
              break
            }
          }
        }

        // console.log("任务开始时间：：")
        // console.log(ls1)
        // console.log(ls1[3].querySelector("td").innerHTML)

        // console.log("任务耗时：：")
        // console.log(ls1)
        // console.log(ls1[1].querySelector("td").innerHTML)

        // console.log("任务开始时间：：")
        // console.log(ls1)
        // console.log(ls1[5].querySelector("td").innerHTML)


        this.rwStepIndex++;
        this.loadRWListDetail();
      }
    },
    loadXQDetail() {
      if (this.stepIndex >= this.xq.length) {
        this.title = '正在获取任务列表'
        this.stepIndex = 0
        this.step = 3
        this.loadRWDetail()
        return
      }
      var webview = document.getElementById("web_cd");
      let url = this.xq[this.stepIndex].url
      webview.loadURL(url);
    },
    loadRWDetail() {
      if (this.stepIndex >= this.xq.length) {
        this.stepIndex = 0
        this.step = 4
        this.rwStepIndex = 0
        this.title = '正在获取任务详细'
        this.loadRWListDetail()
        return
      }
      var webview = document.getElementById("web_cd");
      let url = this.xq[this.stepIndex].rwUrl

      if (url) {
        webview.loadURL(url);
      } else {
        this.stepIndex++
        this.loadRWDetail()
      }
    },
    loadRWListDetail() {
      if (this.stepIndex >= this.xq.length) {
        this.title = '正在写出文件'
        this.buildFile()
        return
      }

      if (!this.xq[this.stepIndex].rwlb || this.rwStepIndex >= this.xq[this.stepIndex].rwlb.length) {
        //下一个
        this.stepIndex++
        this.rwStepInde = 0
        this.loadRWListDetail()
        return
      }

      var webview = document.getElementById("web_cd");
      let url = this.xq[this.stepIndex].rwlb[this.rwStepIndex].url

      if (url) {
        webview.loadURL(url);
      } else {
        this.rwStepIndex++
        this.loadRWListDetail()
      }
    },
    //获取需求任务列表详情
    buildXQRwDetail() {
      var webview = document.getElementById("web_cd");
      var script = `var evt = document.createEvent("HTMLEvents");
        evt.initEvent("input", true, true);
        setTimeout(function(){
            var cell = document.querySelector(".main-col .cell");
            console.log("awork4::"+cell.innerHTML)
        },500)
        `;
      webview.executeJavaScript(script);
    },
    //获取需求详情
    buildXQDetail() {
      var webview = document.getElementById("web_cd");
      var script = `var evt = document.createEvent("HTMLEvents");
        evt.initEvent("input", true, true);
        setTimeout(function(){
            var cell = document.querySelector(".main-col .cell");
            console.log("awork2::"+cell.innerHTML)
        },500)
        `;
      webview.executeJavaScript(script);
    },
    buildRWDetail() {
      var webview = document.getElementById("web_cd");
      var script = `var evt = document.createEvent("HTMLEvents");
        evt.initEvent("input", true, true);
        setTimeout(function(){
            var tbody = document.querySelector("tbody");
            console.log("awork3::"+tbody.innerHTML)
        },500)
        `;
      webview.executeJavaScript(script);
    },
    stopLoading(e) {
      var webview = document.getElementById("web_cd");
      var url = webview.getAttribute("src");
      if (this.step == 1) {
        if (this.onBuild && url.indexOf(this.buildUrl) == 0) {
          this.build()
        }
        return
      }
      if (this.step == 2) {
        this.buildXQDetail()
        return
      }
      if (this.step == 3) {
        this.buildRWDetail()
        return
      }
      if (this.step == 4) {
        this.buildXQRwDetail()
        return
      }
    },
    build() {
      var webview = document.getElementById("web_cd");
      var url = webview.getAttribute("src");
      this.buildUrl = url
      this.onBuild = true;
      this.title = '正在获取需求列表'
      this.step = 1

      // if (url.indexOf(this.buildUrl) != 0) {
      //   webview.loadURL(this.buildUrl);
      //   return
      // }
      var script = `var evt = document.createEvent("HTMLEvents");
        evt.initEvent("input", true, true);
        setTimeout(function(){
            var trs = document.querySelectorAll("tbody tr");
            for (let i = 0; i < trs.length; i++) {
                console.log("awork1::"+trs[i].innerHTML)
            }
            console.log("awork1::finish")
            
        },500)
        `;
      webview.executeJavaScript(script);
    }
  },
};
</script>

<style scoped lang="less">
.operation {
  position: fixed;
  right: 20px;
  bottom: 20px;
  background: #fff;
  padding: 4px 20px;
  border-radius: 100px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4);
}
.build {
  z-index: 99;
  background:rgba(0, 0, 0, 0.6);
  top: 0;
  left: 0;
  position: fixed;
  width: 100%;
  height: 100%;
  text-align: center;
  padding-top: 300px;
  color: #fff;
}
.webview {
  width: 100%;
  height: 100%;
}
</style>
